﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

namespace BrokerBase.Lib.Product
{
    public class ExpandExpress:IExpandExpress
    {
        private bool isComiled;
        private IProductExpander expander;

        public virtual int Id { get; set; }

        public virtual string Code { get; set; }

        public virtual IProductExpander Expander 
        { 
            get
            {
                if(!isComiled)
                {
                    string result=string.Empty;
                    Compile(out result);
                }

                return expander;
            }
        }

        public virtual bool IsVerify 
        {
            get
            {
                return Expander != null;
            }
        }

        public virtual bool Compile(out string result)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters par = new CompilerParameters();

            par.ReferencedAssemblies.Add("System.dll");
            par.ReferencedAssemblies.Add("System.Core.dll");
            par.ReferencedAssemblies.Add("mscorlib.dll");
            par.ReferencedAssemblies.Add("BrokerBase.Lib.dll");

            par.GenerateExecutable = false;
            par.GenerateInMemory = true;

            bool succes = false;

            if (string.IsNullOrEmpty(Code))
            {
                result = "代码为空";
                return false;
            }

            CompilerResults compile = provider.CompileAssemblyFromSource(par, new string[] { Code });

            if (compile.Errors.HasErrors)
            {
                result = "编译失败";
                foreach (CompilerError e in compile.Errors)
                {
                    result += Environment.NewLine + e.ErrorText;
                    Console.WriteLine(e.ErrorText);
                }
            }
            else
            {
                result = "编译成功!";
                isComiled = true;
                succes = true;

                Assembly dyAssembly = compile.CompiledAssembly;
                
                expander = (IProductExpander)dyAssembly.CreateInstance("BrokerBase.Lib.Product.ProductExpander");

            }

            return succes;
        }

    }
}
